<?PHP
/**
 * User: Paulo Fournier
 * Date: 17-08-2013
 * Type: application/json
 * Used to add a new POI to the database
 */

require_once '../../../../php/settings/config.php';
require_once '../../../../php/lib/user.php';

session_start();

$success = FALSE; //used to check if the process was finished successfully
$newId = -1; //will contain the new POI ID, if successfully

$user = unserialize($_SESSION["user"]);

$request_body = file_get_contents('php://input');

$values = json_decode($request_body, TRUE);

//set poi object
$poi = array(
    'id_category' => (int)$values['category'],
    'id_user' => $user->userId,
    'id_group' => $user->groupId,
    'id_image' => DEFAULT_POI_IMAGE_ID,
    'latitude' => $values['latitude'],
    'longitude' => $values['longitude'],
    'radius' => $values['radius'],
    'alias' => $values['name'],
    'validated' => $user->roleId == 3 ? 0 : 1,
    'description' => $values['description'],
    'max_auth_stop_time' => $values['maximumTimeOfPermanence']
);

$ch = curl_init(CRUD_URL . "/Poi");
//set connection paramaters
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "charset: UTF-8", "Accept: application/json"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($poi));

//get response
$rst = curl_exec($ch);

//check if request was successful
if ($rst === false) {
    $err = curl_error($ch);
    $errorCode = 2;

    error_log("request: NOK");
    error_log('Curl error: ' . $err);
}
else {

    try {

        $json = json_decode($rst, TRUE);

        /***
         * Result example
         * ERROR:  {"success":false,"messageError":"56670, The mandatory attributes are not in json.","errorCode":56670,"retVal":null}
         * SUCCESS: {"success":true,"messageError":null,"errorCode":0,"retVal":{"id":91405}}
         */

        //check if procedure was successful
        if (!$json["success"]) {

            error_log("request: NOK");
            error_log("POI: ".json_encode($poi));
            error_log("errorCode: " . $json["errorCode"]);
            error_log("messageError: " . $json["messageError"]);
            error_log("Response: " . $rst);

        } else {
            $newId = $json["retVal"]["id"];
            error_log("success => id: ".$newId);
            $success = TRUE;
        }

    } catch (Exception $e) {

        error_log("request: NOK");
        error_log("POI: ".json_encode($poi));
        error_log("Message: ". $e->getMessage());
        error_log("Response: ". $rst);
    }
}

echo json_encode(array(
    "success" => $success,
    "newId" => $newId
));